package com.im.service.websocket.message.impl;

import com.alibaba.fastjson.JSON;
import com.im.service.infra.entity.ChatHistory;
import com.im.service.service.ChatHistoryService;
import com.im.service.websocket.message.MessageProcessor;
import com.im.service.websocket.message.dto.SentMessage;
import com.im.service.websocket.message.enums.MessageStatus;
import com.im.service.websocket.message.enums.MessageType;
import com.im.service.websocket.session.SessionManager;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

import java.time.LocalDateTime;
import java.util.UUID;

@Service
@RequiredArgsConstructor
@Slf4j
public class DirectChatMessageProcessor implements MessageProcessor {
    private final ChatHistoryService chatHistoryService;

    @Override
    public Mono<Void> process(String senderId, SentMessage sentMessage) {
        return Mono.just(buildChatHistory(senderId, sentMessage))
                .flatMap(it -> SessionManager.getSender(sentMessage.getTargetId()).sendMessage(it))
                .flatMap(chatHistoryService::saveChatHistory)
                .then();
    }

    private ChatHistory buildChatHistory(String senderId, SentMessage sentMessage) {
        return ChatHistory.builder().id(UUID.randomUUID().toString().replace("-", ""))
                .senderId(senderId)
                .receiverId(sentMessage.getTargetId())
                .sentSuccessTime(LocalDateTime.now())
                .msgBody(sentMessage.getContent())
                .msgStatus(MessageStatus.UNREAD.name())
                .build();
    }

    @Override
    public MessageType messageType() {
        return MessageType.DIRECT_MESSAGE;
    }
}
